#include "mythread.h"
#include <QElapsedTimer>  //计算执行时间的类
#include <QtGlobal>
#include <QThread>
Generate::Generate(QObject *parent)
    : QObject{parent}
{

}

void Generate::working(int num)
{
    qDebug() <<"生成随机数的线程的地址："<<QThread::currentThread();  //输出当前线程的地址
    QVector<int> list;
    QElapsedTimer time;
    time.start();
    for (int i=0;i<num;i++){
        list.push_back(rand() % 100000);
    }
    int milsec = time.elapsed();

    qDebug() <<"生成"<<num<<"个随机数总共用时"<<milsec<<"毫秒";
    emit sendArray(list);
}
//------------------------------------------------------------冒泡排序
BubbleSort::BubbleSort(QObject *parent) :QObject(parent)
{

}

void BubbleSort::working(QVector<int> list)
{
    qDebug() <<"冒泡排序的线程的地址："<<QThread::currentThread();  //输出当前线程的地址
    QElapsedTimer time;
    time.start();
    int temp;
    for (int i=0;i<list.size();++i){
        for(int j = 0;j<list.size()-i-1;++j){
            if(list[j]>list[j+1]){
                temp = list[j];
                list[j] = list[j+1];
                list[j+1] = temp;
            }
        }
    }
    int milsec = time.elapsed();

    qDebug() <<"冒泡排序总共用时"<<milsec<<"毫秒";
    emit Finish_Array(list);
}
//------------------------------------------------------------快速排序
void QuickSort::quickSort(QVector<int> &s, int l, int r) {
    if (l >= r) return;  // 递归结束条件
    int pivot = s[l];  // 基准元素
    int i = l, j = r;
    while (i < j) {
        while (i < j && s[j] >= pivot) j--;
        if (i < j) s[i++] = s[j];
        while (i < j && s[i] <= pivot) i++;
        if (i < j) s[j--] = s[i];
    }
    s[i] = pivot;
    quickSort(s, l, i - 1);  // 对左边子序列进行快速排序
    quickSort(s, i + 1, r);  // 对右边子序列进行快速排序
}

QuickSort::QuickSort(QObject *parent):QObject(parent)
{

}


void QuickSort::working(QVector<int> list)
{
    qDebug() <<"快速排序的线程的地址："<<QThread::currentThread();  //输出当前线程的地址
    QElapsedTimer time;
    time.start();

    quickSort(list,0,list.size()-1);

    int milsec = time.elapsed();

    qDebug() <<"快速排序总共用时"<<milsec<<"毫秒";
    emit Finish_Array(list);
}
